<template>
    <div class=" map-zoom">
        <div class="amap-page-container map-areas" :style="{height: mapHeights}">
            <el-amap
                    :vid="'map-area' + randomNum"
                    ref="map"
                    :mapStyle="mapStyle"
                    :amap-manager="amapManager"
                    :zoom="zoom"
                    :plugin="plugin"
                    :center="mapCenter"
                    :style="{height: mapHeights}"
                    class="amap-demo">
                <template v-for="(polygon, index) in polygonsText">
                    <el-amap-text :text="polygon.contentRender"
                                  :events="polygon.events"
                                  v-if="polygon.isShow"
                                  textAlign="center"
                                  verticalAlign="center"
                                  :position="polygon.position">
                    </el-amap-text>
                </template>
                <template v-for="(polygon, index) in polygonsEdit">
                    <el-amap-polygon
                            :vid="index" :ref="`polygon_${index}`"
                            :path="polygon.path"
                            fillOpacity="0.4"
                            v-if="polygon.isShow"
                            :strokeColor="polygon.borderColor"
                            :fillColor="polygon.bgColor"
                            :draggable="polygon.draggable"
                            :editable="polygon.editable"
                            :events="polygon.events">
                    </el-amap-polygon>
                </template>
            </el-amap>
            <div class="draw-popup">
                <div class="list-box" :style="{height: rightList}">
                    <template v-for="(item,index) in polygonsEdit">
                        <div
                            class="list"
                            @click="selectArea(item.id)"
                            :style="item.isShow?{borderColor:item.borderColor}:{borderColor:'#eee',color:'#000'}">
                                <div :style="item.isShow?{backgroundColor: item.bgColor,opacity: 0.4}:{backgroundColor: '#eee',opacity: 0.4}">{{item.contentRender}}</div>
                        </div>
                    </template>

                </div>

            </div>
            <div class="drawEnclosure" v-if="showButton">
                <div class="button-group">
                    <input type="button" class="btn btn_primary" value="添加区域" @click="addArea"/>&nbsp;
                    <input type="button" class="btn btn_primary" value="全屏" @click="fullScreen"/>&nbsp;
                    <input type="button" class="btn btn_primary" value="还原地图" @click="narrowScreen"/>&nbsp;
                </div>
            </div>
            <div class="select-style">
                <el-select v-model="mapStyle" placeholder="请选择主题" style="width: 100px;">
                    <el-option
                            v-for="item in themeData"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </div>
        </div>
    </div>
</template>


<script>
    import color from '../../init/color.js'
    import VueAMap from "vue-amap";
    import Vue from "vue";
    let amapManager = new VueAMap.AMapManager();
    export default {
        props: {
            polygonObj: {
                type: Array,
                default: () => {
                    return []
                }
            },
            mapHeight: {
                type: String,
                default: '400px'
            },
            showButton: {
                type: Boolean,
                default: true
            },
            edit: {
                type: Boolean,
                default: true
            }
        },
        data() {
            return {
                mapStyle: 'amap://styles/whitesmoke',
                themeData: [
                    {
                        label: '标准',
                        value: 'amap://styles/normal'
                    },
                    {
                        label: '远山黛',
                        value: 'amap://styles/whitesmoke'
                    },
                    {
                        label: '幻影黑',
                        value: 'amap://styles/dark'
                    },
                    {
                        label: '月光银',
                        value: 'amap://styles/light'
                    },
                    {
                        label: '草色青',
                        value: 'amap://styles/fresh'
                    },
                    {
                        label: '雅士灰',
                        value: 'amap://styles/grey'
                    },
                    {
                        label: '涂鸦',
                        value: 'amap://styles/graffiti'
                    },
                    {
                        label: '马卡龙',
                        value: 'amap://styles/macaron'
                    },
                    {
                        label: '靛青蓝',
                        value: 'amap://styles/blue'
                    },
                    {
                        label: '极夜蓝',
                        value: 'amap://styles/darkblue'
                    },
                    {
                        label: '酱籽',
                        value: 'amap://styles/wine'
                    }
                ],
                saveBase: [],
                saveChange: [],
                isEditKey: null,
                isEdit: false,
                randomNum: Math.floor(Math.random() * 1000000000000000 + 1),
                amapManager: amapManager,
                zoom: 10,
                mapCenter: [116.403322, 39.820255],
                plugin: [],
                mapHeights: '',
                rightList: '350px',
                polygonsEdit: [],
                polygonsText: [],
                savePolygonsEdit: []
            };
        },
        watch: {
            polygonObj: {
                handler() {
                    this.saveBase = this.polygonObj;
                    this.initarea();
                },
                deep: true

            },
            mapHeight: function (val) {
                this.mapHeights = val;
            }
        },
        mounted() {
            this.mapCenter = JSON.parse(localStorage.getItem('lnglat'));
        },
        methods: {
            addArea() {
                this.$emit('openDialog', '');
            }, // 添加区域
            fullScreen() {
                this.mapHeights = '86vh';
                this.rightList = '80vh';
            }, // 全屏
            narrowScreen() {
                this.mapHeights = '400px';
                this.rightList = '350px';
            }, // 还原地图
            selectArea(valueId) {
                // console.info('点击区域', valueId);
                for (let key in this.polygonsEdit) {
                    if (valueId == this.polygonsEdit[key].id) {
                        if (this.polygonsEdit[key].isShow) {
                            this.polygonsEdit[key].isShow = false;
                            this.polygonsText[key].isShow = false;

                        } else {
                            this.polygonsEdit[key].isShow = true;
                            this.polygonsText[key].isShow = true;
                        }
                    }
                }
            }, // 切换显示区域
            changeArea(value) {  // 编辑区域
                let areaAge = AMap.GeometryUtil.ringArea(this.saveChange);
                let params = {
                    area: JSON.stringify(this.saveChange),
                    name: value.name,
                    acreage: areaAge,
                    ranking: value.ranking,
                    site: value.site,
                    status: value.status,
                    type: value.type
                };
                this.$http.put('express/area/' + value.id, params)
                    .then((response) => {
                        this.$message({
                            type: 'success',
                            message: response.data.msg
                        });
                        for (let key in this.saveBase) {
                            if (this.saveBase[key].id == response.data.data.id) {
                                this.saveBase[key] = response.data.data
                            }
                        }
                        // this.initarea();
                    })
                    .catch((error) => {
                        if (error.response.data.msg) {
                            this.$message.error(error.response.data.msg);
                        } else {
                            this.$message.error('请求错误：' + error.response.status);
                        }
                    });
            },
            getSum(total, num) {
                return total + num;
            },  // 二维数组平均值函数
            averageColRow(arr) {
                let _this = this;
                let Max = 0;
                arr.map(function (item) {
                    Max = Math.max(Max, item.length);
                })
                let result = Array(Max).fill("")
                    .map(function (_e, outerIndex) {
                        return arr.map(function (e, innerIndex, input) {
                            return e[outerIndex]
                        }).filter(function (ele) {
                            return ele !== undefined
                        })
                    });

                let permutationArray = result.map(function (item) {
                    {
                        return item.filter(function (ele) {
                            return ele != 0;
                        })
                    }

                });
                return permutationArray.map(function (item) {
                    // console.info('平局值', item.reduce(_this.getSum,0)/item.length);
                    return item.reduce(_this.getSum, 0) / item.length;
                })

            },  // 二维数组平均值函数
            initarea() {  // 初始化地图
                this.isEditKey = null;
                const self = this;
                self.polygonsEdit = [];
                self.polygonsText = [];
                for (let index in self.saveBase) {
                    self.polygonsText.push({
                        isShow: true,
                        contentRender: self.saveBase[index].name,
                        position: self.averageColRow(JSON.parse(self.saveBase[index].area)),
                        events: {
                            click: () => {
                                self.$emit('openDialog', self.saveBase[index].id);
                            }
                        }
                    });
                }
                if (self.edit) {  // 可编辑
                    for (let key in self.saveBase) {
                        self.polygonsEdit.push({
                            editable: false,
                            isShow: true,
                            id: self.saveBase[key].id,
                            contentRender: self.saveBase[key].name,
                            draggable: false,
                            bgColor: color[key],
                            borderColor: color[key],
                            path: self.saveBase[key].area ? JSON.parse(self.saveBase[key].area) : [],
                            events: {
                                click: () => {
                                    if (!self.isEditKey) {
                                        self.isEditKey = key;
                                        Vue.set(self.polygonsEdit[key], 'editable', true);
                                        self.savePolygonsEdit = self.polygonsEdit;
                                    } else {
                                        this.$confirm('是否保存修改?', '提示', {
                                            distinguishCancelAndClose: true,
                                            confirmButtonText: '确定',
                                            cancelButtonText: '还原',
                                        }).then(action => {
                                            Vue.set(self.polygonsEdit[self.isEditKey], 'editable', false);
                                            setTimeout(() => {
                                                self.changeArea(self.saveBase[self.isEditKey]);
                                                self.isEditKey = null;
                                                self.polygonsEdit = self.savePolygonsEdit;
                                            }, 400);

                                        }).catch(action => {
                                            if (action === 'cancel') {
                                                // self.initarea();
                                                Vue.set(self.polygonsEdit[self.isEditKey], 'editable', false);
                                                self.polygonsEdit[self.isEditKey].path = JSON.parse(self.saveBase[self.isEditKey].area);
                                                self.isEditKey = null;

                                                console.info('self.polygonsEdit',self.polygonsEdit);
                                            } else if (action === 'close') {
                                                return;
                                            }
                                        });


                                    }
                                },
                                end: (e) => {
                                    let newPath = e.target.getPath().map(point => [point.lng, point.lat]);
                                    // console.info('变化的经纬度', JSON.stringify(newPath));
                                    self.saveChange = newPath;
                                }
                            }
                        });
                    }
                } else {
                    for (let key in self.saveBase) {
                        self.polygonsEdit.push({
                            editable: false,
                            isShow: true,
                            id: self.saveBase[key].id,
                            contentRender: self.saveBase[key].name,
                            draggable: false,
                            bgColor: color[key],
                            borderColor: color[key],
                            path: self.saveBase[key].area ? JSON.parse(self.saveBase[key].area) : [],
                            events: {
                                click: () => {
                                    if (!self.edit) {
                                        return;
                                    }
                                }
                            }
                        });
                    }
                }
                // this.mapCenter = self.saveBase[0] && JSON.parse(self.saveBase[0].area) ? JSON.parse(self.saveBase[0].area)[0] : [116.403322, 39.820255];
            }
        }
    };
</script>
<style lang="less">
    .map-areas {
        .amap-overlay-text-container {
            font-size: 12px !important;
            border: none !important;
            color: #000 !important;
            line-height: 20px;
            height: 20px;
        }
        .amap-overlay-text-container:hover {
            color: #009688 !important;
            background: #eee !important;
        }
    }

</style>
<style lang="less" scoped>
    @import url('./map.less');

    .amap-page-container {
        width: 100%;
        height: 400px;
        position: relative;
        padding-bottom: 0px;
        .select-style {
            position: absolute;
            top: 10px;
            left: 10px;
        }
        .search-box {
            position: absolute;
            top: 20px;
            left: 80px;
        }
        .draw-popup {
            width: 108px;
            /*height: 800px;*/
            /*background-color: rgba(255,255,255,0.6) ;*/
            position: absolute;
            top: 6px;
            right: 10px;
            .title {
                width: 100%;
                height: 50px;
                text-align: center;
                line-height: 50px;
                color: #fff;
                position: absolute;
                top: 0px;

                background-color: #009688;
            }
            .list-box {
                /*height: 800px;*/
                /*width: 100px;*/
                overflow-y: scroll;

            }
            .list-box::-webkit-scrollbar {
                width: 1px;
            }
            .list {
                width: 112px;
                /*height: 30px;*/
                text-align: center;
                cursor: pointer;
                color: #fff;
                /*padding: 4px 0;*/
                margin-bottom: 2px;
                /*line-height: 30px;*/
                opacity: 1;
                border: 3px solid;
            }
        }
    }

</style>


